<?php namespace Common\Model;

use Hdphp\Model\Model;

//城市表
class City extends Model{
	//定义模型
	protected $table = "city";
	//自动验证
	protected $validate=array(
		array('city_name','required','城市名称不能为空',3,3),
		array('city_name','maxlen:50','城市名称不能大于50个字',3,3),
		array('city_sort','required','城市排序不能为空',3,3),
	);

	//添加城市
	public function store(){
		if ($this->create()) {
			$cityArr=explode('|',Q('post.city_name'));
			foreach ($cityArr as $v) {
				$this->add(array(
					'city_name'=>$v,
					'city_sort'=>Q('post.city_sort'),
					'city_pid'=>Q('post.city_pid'),
				));
			}
			Cache::del('cityData');
			Cache::del('otherCity');
			return true;
		}
		return false;
	}

	//获得除了自己和自己子集的所有数据
	public function notMy($cid){
		//获得自己的所有子集
		$cids=$this->getSon($cid);
		//压入自己
		$cids[]=$cid;
		return $this->where("city_id not in (".implode(',',$cids).")")->get();
	}

	//获得自己的子集
	public function getSon($cid){
		$tmp=[];
		foreach ($this->get() as $value) {
			if ($value['city_pid']==$cid) {
				$tmp[]=$value['city_id'];
				$tmp=array_merge($tmp,$this->getSon($value['city_id']));
			}
		}
		return $tmp;
	}

	//编辑分类
	public function edit(){
		if ($this->create()) {
			$this->save();
			return true;
		}
		return false;
	}

	//获得所有的省
	public function shengs(){
		$shengs=$this->where("city_pid=0")->lists('city_id');
        $shengs=implode(',',$shengs);
        return $shengs;
	}

	//第一排热门城市
	public function hotCity(){
        $cityData=Cache::get('cityData');
        if (!$cityData) {
            $shengs=$this->shengs();
            $cityData=$this->where("city_pid IN ({$shengs})")->orderBy('city_sort','ASC')->limit(3)->get();
            Cache::set('cityData',$cityData,0);
        }
        return $cityData;
	}

	//其他城市
	public function otherCity(){
        $otherCity=Cache::get('otherCity');
        if (!$otherCity) {
        	$shengs=$this->shengs();
            $cityDatas=$this->where("city_pid IN ({$shengs})")->orderBy('city_sort','ASC')->limit(3)->lists('city_id');
            $strCity=implode(',',$cityDatas);
            $otherCity=$this->where("city_pid IN ({$shengs}) AND city_id NOT IN ({$strCity})")->orderBy('city_sort','ASC')->get();
            Cache::set('otherCity',$otherCity,0);
        }
        return $otherCity;
	}

	//选中城市及地区
    public function chooseCity($a,$b=1){
    	$showCity=[];
        //被选中的城市
        $param=isset($_GET['param'])? explode('_', Q('get.param')) : array_fill(0,$a,0);
        $defaultCid=$param[0];
        $defaultCity=$this->where("city_id=$defaultCid")->pluck('city_name');
        $showCity['active']=$defaultCity;

        //选中城市下的地区
        if ($b==2) {
            $areaData=$this->where("city_pid=$defaultCid")->get();
            $showCity['son']=$areaData;
            $showArea=$this->where("city_id={$param[1]}")->pluck('city_name');
            $showArea=$showArea?$showArea:'不限';
            $showCity['area']=$showArea;
        }
        return $showCity;
    }


}